package org.springside.examples.showcase.schedule;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springside.examples.showcase.wb.entity.WbContent;
import org.springside.examples.showcase.wb.service.WbContentManager;

/**
 * 被Spring的Quartz JobDetailBean定时执行的Job类, 支持持久化到数据库实现Quartz集群.
 * 
 * 因为需要被持久化, 不能有用XXManager等不能被持久化的成员变量, 只能在每次调度时从QuartzJobBean注入的applicationContext中动态取出.
 */
public class QuartzClusterableJob extends QuartzJobBean {
	private static Logger logger = LoggerFactory.getLogger(QuartzClusterableJob.class);
	private ApplicationContext applicationContext;

	/**
	 * 从SchedulerFactoryBean注入的applicationContext.
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	/**
	 * 定时打印当前用户数到日志.
	 */
	@Override
	protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
		WbContentManager wbContentManager = applicationContext.getBean(WbContentManager.class);
		List<WbContent> needDownLoadFeeds = wbContentManager.getNeedDownLoadFeeds("2012-02-11");
		List<WbContent> needInsertFeeds = new ArrayList<WbContent>();
		for (WbContent wbContent : needDownLoadFeeds) {
			WbContent wb = new WbContent();
			logger.info("uid:{} mid:{}", wbContent.getIr_uid(), wbContent.getIr_mid());
			WbContent downloadHotFeeds = null;
			try {
				downloadHotFeeds = wbContentManager.downloadHotFeeds("" + wbContent.getIr_uid(), "" + wbContent.getIr_mid());
				if (downloadHotFeeds.getIr_mid() == 0l || StringUtils.isEmpty(downloadHotFeeds.getIr_created_date())) {
					continue;
				}
				BeanUtils.copyProperties(downloadHotFeeds, wb);
				logger.info("mid:{} screen_name:{}", wb.getIr_mid(), wb.getIr_screen_name());
				needInsertFeeds.add(wb);
				// wbContentManager.saveHotFeeds(wbContent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		wbContentManager.save(needInsertFeeds);
	}
}
